package com.yu.util;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Arrays;

import javax.imageio.ImageIO;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;  
  
  
public class SendPostMethod {  
    @SuppressWarnings("resource")
	public String post(String file,String multipartkey,String imagetype) throws Exception{
    	String result = null;
    	String format = file.toLowerCase().substring(file.lastIndexOf(".") +1);
    	
    	String url = "http://file.carmap.me:9000/club/api/resource/upload/61034864334556?multipartkey="+multipartkey+"&format="+format+"&imagetype="+imagetype;
    	System.out.println(url);
    	HttpPost httpPost = new HttpPost(url);
    	//httpPost.setHeader("Content-Type", "multipart/form-data");
    	//httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("uid", "61034864334556");
        httpPost.setHeader("udid", "web-admin");
        httpPost.setHeader("sn", "sn1234");
        httpPost.setHeader("sign", "sp_youche3");
        httpPost.setHeader("token", "e446616d-19a9-426b-835c-4433e51fe1e9-it09vq16");
        httpPost.setHeader("Content-MD5", "707dad8305e29ace6de55d9d575497c1");
        httpPost.setHeader("User-Agent", "UCar/1.0 (iPhone; iOS 9.3.2; Scale/2.00)");
        
    	MultipartEntity mutiEntity = new MultipartEntity();
	    mutiEntity.addPart("capturetime",new StringBody("1476862278", Charset.forName("utf-8")));
        mutiEntity.addPart("restype",new StringBody("0", Charset.forName("utf-8")));
        mutiEntity.addPart("subtype",new StringBody("0", Charset.forName("utf-8")));
        mutiEntity.addPart("lat",new StringBody("22.3", Charset.forName("utf-8")));
        mutiEntity.addPart("lon",new StringBody("122.3", Charset.forName("utf-8")));
        try {
        	BufferedImage bufferedImage = ImageIO.read(new File(file));   
            int width = bufferedImage.getWidth();   
            int height = bufferedImage.getHeight();   
            mutiEntity.addPart("info",new StringBody(width+"*"+height, Charset.forName("utf-8")));
        	mutiEntity.addPart("image", new FileBody(new File(file)));
        } catch(Exception e){
        	
        }
        
    	httpPost.setEntity(mutiEntity);
    	HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);  
        if(httpResponse.getStatusLine().getStatusCode() == 200){  
            HttpEntity httpEntity = httpResponse.getEntity();  
            System.out.println("result:"+result);
            result = EntityUtils.toString(httpEntity);//取出应答字符串  
        }  
    	return result;
    }
 
    public  String methodPost(String url,NameValuePair[] data,String file){  
          
        String response= "";//要返回的response信息  
        
        // 执行postMethod  
        int statusCode = 0;  
        PostMethod postMethod = null;
        try {  
        	//FilePart：用来上传文件的类  
            FilePart fp = new FilePart("image", new File(file));  
            Part[] parts = { fp };  
  
            HttpClient httpClient = new HttpClient(); 
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(50000);// 设置连接时间
            postMethod = new PostMethod(url);
            
            //对于MIME类型的请求，httpclient建议全用MulitPartRequestEntity进行包装  
            MultipartEntity mutiEntity = new MultipartEntity();
            mutiEntity.addPart("desc",new StringBody("美丽的西双版纳", Charset.forName("utf-8")));
            mutiEntity.addPart("pic", new FileBody(new File(file)));
            //postMethod.setRequestEntity(mutiEntity);  
             /*
            httpPost.setEntity(mutiEntity);
            MultipartRequestEntity mre = new MultipartRequestEntity(parts, postMethod.getParams());  
            postMethod.setRequestEntity(mre);  
            */
            // 将表单的值放入postMethod中
            postMethod.setRequestHeader("Accept", "application/json");
            postMethod.setRequestHeader("uid", "61034864334556");
            postMethod.setRequestHeader("udid", "web-admin");
            postMethod.setRequestHeader("sn", "sn1234");
            postMethod.setRequestHeader("sign", "sp_youche3");
            postMethod.setRequestHeader("token", "e446616d-19a9-426b-835c-4433e51fe1e9-it09vq16");
            postMethod.setRequestHeader("Content-MD5", "707dad8305e29ace6de55d9d575437c1");
            postMethod.setRequestHeader("User-Agent", "UCar/1.0 (iPhone; iOS 9.3.2; Scale/2.00)");
            postMethod.setRequestHeader("enctype", "multipart/form-data");
            postMethod.setRequestHeader("Accept", "application/json");
            postMethod.setRequestBody(data);  
            
            statusCode = httpClient.executeMethod(postMethod);
            System.out.println(postMethod.getStatusLine());  
            
            try {  
                response= postMethod.getResponseBodyAsString();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
             
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {
        	 postMethod.releaseConnection();
		}   
        
        
        return response;  
    }  
  
   
    public static void main(String[] args) throws Exception {  
    	
    	//System.out.println(new SendPostMethod().post("D:\\img\\1.gif"));
    	File file = new File("D:\\img\\持剑带字系列表情\\");
    	File [] files = file.listFiles();
        for(File a:files) {
            System.out.println(new SendPostMethod().post(file.getAbsoluteFile()+"\\"+a.getName(),"image","system"));
        }
    	/*
    	String test = "{\"code\": 0,\"cost\": 19}";
    	JSONObject obj = JSONObject.fromObject(test);
    	System.out.println(obj.get("code"));
    	System.out.println(obj.get("cost"));
    	String resid = "1.png";
    	StringBuffer sb = new StringBuffer();
    	sb.append("	INSERT IGNORE into club_face (resid ,type,subtype,`group`,format,status,info,createtime,valid) VALUES ( ");
    	sb.append("'"+resid+"',6,1,'default','png',1,'30*30',"+System.currentTimeMillis()+",0");
    	sb.append(")");
    	System.out.println(sb.toString());
        
    	
        String url = "http://file.carmap.me:9000/club/api/face/upload/61034864334556?multipartkey=image&format=png&imagetype=face"; 
        
        NameValuePair capturetime = new NameValuePair("capturetime", "1476262278");
        NameValuePair restype = new NameValuePair("restype", "101");
        NameValuePair subtype = new NameValuePair("subtype", "0");
        NameValuePair info = new NameValuePair("info", "30*30");
        NameValuePair[] data = {capturetime,restype,subtype,info}; 
        String response=new SendPostMethod().methodPost(url,data,"D:\\img\\spring.png");
        System.out.println("********"+response);
        */
       
    }  
  
}  